package top.fengyulou.xiaofeng.common;

import cn.hutool.poi.word.Word07Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

public class WebUtils {
    /**
     * 重定向
     *
     * @param uri
     * @return
     */
    public static String redirect(String uri) {
        return "redirect:" + uri;
    }

    /**
     * 判断是否是ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }

    /**
     * 使用hutool导出Word文件并下载
     * @param response
     * @param fileName
     * @param writer
     * @throws IOException
     */
    public static void dowWordFile(HttpServletResponse response, String fileName, Word07Writer writer) throws IOException {
        response.addHeader("Content-Type", "application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName+".docx", "utf-8"));
        writer.flush(response.getOutputStream());
        writer.close();
    }
}
